package com.beemans.topon.demo.ui.fragments

import android.util.Log
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.beemans.common.ui.fragments.CommonFragment
import com.beemans.common.utils.ToastUtils
import com.beemans.topon.ads2.AdvertManager
import com.beemans.topon.ads2.BannerAdvert
import com.beemans.topon.ads2.BannerAdvertCallback
import com.beemans.topon.ads2.BannerAdvertConfig
import com.beemans.topon.demo.R
import com.beemans.topon.demo.constant.Constant
import com.beemans.topon.demo.databinding.FragmentBannerAdBinding
import com.tiamosu.databinding.delegate.lazyDataBindingOrNull
import com.tiamosu.databinding.page.DataBindingConfig
import com.tiamosu.fly.ext.clickNoRepeat

/**
 * @author tiamosu
 * @date 2020/7/8.
 */
class BannerAdFragment : CommonFragment() {
    private val dataBinding: FragmentBannerAdBinding? by lazyDataBindingOrNull { }
//    private val bannerAdLoader by lazy {
//        val config = TpBannerAd.TpBannerAdConfig(Constant.BANNER_ID, 375.pt2px, 90.pt2px)
//        TpBannerAd.TpBannerAdLoader(this, config, dataBinding?.bannerAdFlAd) {
//            onAdLoaded {
//                Log.e("susu2", "childCount:${dataBinding?.bannerAdFlAd?.childCount}")
//            }
//        }
//    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_banner_ad)
    }

    override fun initEvent() {
        //加载广告并展示
        dataBinding?.bannerAdBtnShow?.clickNoRepeat {
            showAdvert()

//            TpBannerAd.start(bannerAdLoader)
        }
    }

    /**
     * 展示广告
     */
    private fun showAdvert() {
        val flContainer = dataBinding?.bannerAdFlAd ?: return
        val advertConfig = BannerAdvertConfig(Constant.BANNER_ID, 375f / 90)

        AdvertManager.loadBannerAdvert(
            this,
            flContainer,
            advertConfig,
            object : BannerAdvertCallback() {
                override fun onAdvertLoaded(bannerAdvert: BannerAdvert) {
                    printLog("广告加载成功")
                }

                override fun onAdvertLoadFail(bannerAdvert: BannerAdvert, adError: AdError?) {
                    printLog("广告加载失败")
                }

                override fun onAdvertShow(bannerAdvert: BannerAdvert, atAdInfo: ATAdInfo?) {
                    printLog("广告展示")
                }

                override fun onAdvertClicked(bannerAdvert: BannerAdvert, atAdInfo: ATAdInfo?) {
                    printLog("广告点击")
                }

                override fun onAdvertClose(
                    bannerAdvert: BannerAdvert,
                    atAdInfo: ATAdInfo?
                ): Boolean {
                    printLog("广告关闭")
                    return true
                }
            })
    }

    private fun printLog(msg: String) {
        Log.e("susu", msg)
        ToastUtils.showShort(msg)
    }

    override fun doBusiness() {
    }
}